package com.h52mm.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;

import java.nio.charset.StandardCharsets;

public class SetCuratorNodeSample {
    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2182") //server地址
                .sessionTimeoutMs(50000) // 会话超时时间
                .connectionTimeoutMs(300000) // 连接超时时间
                .retryPolicy(retryPolicy) // 重试策略
                .namespace("curator") // 独⽴命名空间/base
                .build(); //
        client.start();
        System.out.println("Zookeeper session established");

        //获取节点数据
        String path = "/test_get";
        Stat stat = new Stat();
        byte[] bytes = client.getData().storingStatIn(stat).forPath(path);
        System.out.println(new String(bytes));
        //更新节点数据
        int version = client.setData().withVersion(stat.getVersion()).forPath(path,"新内容".getBytes(StandardCharsets.UTF_8)).getVersion();
        System.out.println("Success set node for : " + path + ", new version: "+version);
        client.setData().withVersion(stat.getVersion()).forPath(path,"新内容1".getBytes(StandardCharsets.UTF_8)).getVersion();
    }
}
